<template>
  <a-modal
    :title="title"
    :width="1000"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    
    <a-spin :spinning="confirmLoading">
      <!-- 出库单基本信息 -->
      <a-descriptions :title="model.outboundNo" bordered :column="3" style="margin-bottom: 16px;">
        <a-descriptions-item label="出库类型">
          <j-dict-tag v-if="model.outboundType" :value="model.outboundType" dictCode="wms_outbound_type"/>
          <span v-else>-</span>
        </a-descriptions-item>
        <a-descriptions-item label="出库日期">
          {{ model.outboundDate || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="状态">
          <j-dict-tag v-if="model.status" :value="model.status" dictCode="wms_outbound_status"/>
          <span v-else>-</span>
        </a-descriptions-item>
        <a-descriptions-item label="关联订单号" v-if="model.orderNo">
          {{ model.orderNo }}
        </a-descriptions-item>
        <a-descriptions-item label="关联领料单号" :span="2" v-if="model.requisitionNo">
          {{ model.requisitionNo }}
        </a-descriptions-item>
        <a-descriptions-item label="备注" :span="3">
          {{ model.remark || '-' }}
        </a-descriptions-item>
      </a-descriptions>
      
      <!-- 明细信息 -->
      <a-divider orientation="left">明细信息</a-divider>
      <a-table
        ref="detailTable"
        size="small"
        bordered
        rowKey="id"
        :columns="detailColumns"
        :dataSource="model.outboundDetailList"
        :pagination="false"
        style="margin-bottom: 16px;">
        
        <template slot="materialTypeSlot" slot-scope="text">
          <j-dict-tag v-if="text" :value="text" dictCode="material_type"/>
          <span v-else>-</span>
        </template>
        
        <template slot="statusSlot" slot-scope="text">
          <j-dict-tag v-if="text" :value="text" dictCode="wms_outbound_detail_status"/>
          <span v-else>-</span>
        </template>
      </a-table>
      
      <!-- 审核信息 -->
      <a-divider orientation="left">审核信息</a-divider>
      <a-form :form="form">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="审核结果" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-radio-group v-decorator="['isPass', {rules: [{required: true, message: '请选择审核结果!'}]}]">
                <a-radio :value="true">通过</a-radio>
                <a-radio :value="false">驳回</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="审核时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input :value="currentTime" disabled />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="审核意见" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-textarea
            v-decorator="['remark']"
            :rows="3"
            placeholder="请输入审核意见"/>
        </a-form-item>
      </a-form>
    </a-spin>
    
    <!-- 分配方案弹窗 -->
    <allocation-plan-modal 
      ref="allocationPlanModal"
      @confirmed="handleAllocationConfirmed"
      @reallocated="handleAllocationReallocated"
    />
  </a-modal>
</template>

<script>
  import { auditOutbound, getOutboundById } from '@/api/wms/outbound'
  import AllocationPlanModal from './AllocationPlanModal'
  import JDictTag from '@/components/dict/JDictTag'
  
  export default {
    name: "OutboundAudit",
    components: {
      AllocationPlanModal,
      JDictTag
    },
    data () {
      return {
        title: "审核",
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        form: this.$form.createForm(this),
        detailColumns: [
          {
            title: '物料类型',
            align: 'center',
            dataIndex: 'materialType',
            width: 100,
            scopedSlots: { customRender: 'materialTypeSlot' }
          },
          {
            title: '物料编码',
            align: 'center',
            dataIndex: 'materialCode',
            width: 120
          },
          {
            title: '物料名称',
            align: 'center',
            dataIndex: 'materialName',
            width: 150
          },
          {
            title: '规格(长宽高)',
            align: 'center',
            dataIndex: 'specification',
            width: 120
          },
          {
            title: '颜色',
            align: 'center',
            dataIndex: 'color',
            width: 80
          },
          {
            title: '数量',
            align: 'center',
            dataIndex: 'quantity',
            width: 80
          },
          {
            title: '单位',
            align: 'center',
            dataIndex: 'unit',
            width: 60
          },
          {
            title: '批次号',
            align: 'center',
            dataIndex: 'batchNo',
            width: 100
          },
          {
            title: '状态',
            align: 'center',
            dataIndex: 'status',
            width: 80,
            scopedSlots: { customRender: 'statusSlot' }
          }
        ]
      }
    },
    computed: {
      currentTime() {
        return new Date().toLocaleString('zh-CN');
      }
    },
    methods: {
      show(record) {
        this.form.resetFields();
        this.model = {};
        this.visible = true;
        this.loadDetail(record.id);
      },
      
      loadDetail(id) {
        this.confirmLoading = true;
        getOutboundById({id: id}).then(res => {
          if (res.success) {
            this.model = res.result;
          }
        }).finally(() => {
          this.confirmLoading = false;
        })
      },
      handleOk() {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            
            auditOutbound({
              id: that.model.id,
              isPass: values.isPass,
              remark: values.remark
            }).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                
                // 如果审核通过，检查是否有分配结果
                if (values.isPass && res.result && res.result.allocationResult) {
                  that.confirmLoading = false;
                  that.showAllocationPlan(res.result.allocationResult);
                } else if (values.isPass) {
                  // 兼容旧版本，查询分配方案
                  that.queryAndShowAllocationPlan();
                } else {
                  that.confirmLoading = false;
                  that.$emit('ok');
                  that.close();
                }
              } else {
                that.$message.warning(res.message);
                that.confirmLoading = false;
              }
            }).catch(() => {
              that.confirmLoading = false;
            })
          }
        })
      },
      handleCancel() {
        this.close();
      },
      close() {
        this.visible = false;
      },
      
      // 直接显示分配方案（来自审核接口的返回结果）
      showAllocationPlan(allocationResult) {
        // 显示分配方案弹窗
        this.$refs.allocationPlanModal.show(this.model.id, allocationResult);
        
        // 关闭审核弹窗
        this.close();
        this.$emit('ok');
      },
      
      // 查询并显示分配方案
      queryAndShowAllocationPlan() {
        this.$http.get('/wms/outbound/getAllocationPlan', {
          params: { outboundId: this.model.id }
        }).then(res => {
          this.confirmLoading = false;
          
          if (res.success) {
            const allocationPlans = res.result || [];
            
            // 构造分配结果对象
            const allocationResult = this.buildAllocationResult(allocationPlans);
            
            // 显示分配方案弹窗
            this.$refs.allocationPlanModal.show(this.model.id, allocationResult);
            
            // 关闭审核弹窗
            this.close();
            this.$emit('ok');
          } else {
            this.$message.warning('查询分配方案失败：' + (res.message || '未知错误'));
            this.close();
            this.$emit('ok');
          }
        }).catch(err => {
          this.confirmLoading = false;
          console.error('查询分配方案失败:', err);
          this.$message.error('查询分配方案失败');
          this.close();
          this.$emit('ok');
        });
      },
      
      // 构造分配结果对象
      buildAllocationResult(allocationPlans) {
        if (!allocationPlans || allocationPlans.length === 0) {
          return {
            success: true,
            fullySatisfied: false,
            allocationPlans: [],
            unallocatedMaterials: [],
            totalRequiredQuantity: 0,
            totalAllocatedQuantity: 0,
            totalUnallocatedQuantity: 0,
            message: '暂无分配方案'
          };
        }
        
        // 按物料分组统计
        const materialGroups = {};
        let totalRequired = 0;
        let totalAllocated = 0;
        
        allocationPlans.forEach(plan => {
          const key = plan.materialCode;
          if (!materialGroups[key]) {
            materialGroups[key] = {
              materialCode: plan.materialCode,
              materialName: plan.materialName,
              requiredQuantity: plan.requiredQuantity || 0,
              allocatedQuantity: 0,
              unit: plan.unit
            };
          }
          materialGroups[key].allocatedQuantity += (plan.allocationQuantity || 0);
        });
        
        // 计算未满足的物料
        const unallocatedMaterials = [];
        let fullySatisfied = true;
        
        Object.values(materialGroups).forEach(material => {
          totalRequired += material.requiredQuantity;
          totalAllocated += material.allocatedQuantity;
          
          if (material.allocatedQuantity < material.requiredQuantity) {
            fullySatisfied = false;
            unallocatedMaterials.push({
              materialCode: material.materialCode,
              materialName: material.materialName,
              requiredQuantity: material.requiredQuantity,
              availableQuantity: material.allocatedQuantity,
              shortageQuantity: material.requiredQuantity - material.allocatedQuantity,
              unit: material.unit
            });
          }
        });
        
        return {
          success: true,
          fullySatisfied,
          allocationPlans,
          unallocatedMaterials,
          totalRequiredQuantity: totalRequired,
          totalAllocatedQuantity: totalAllocated,
          totalUnallocatedQuantity: totalRequired - totalAllocated,
          message: fullySatisfied ? '分配完成，完全满足需求' : '分配完成，但部分物料库存不足'
        };
      },
      
      // 分配方案确认回调
      handleAllocationConfirmed(allocationResult) {
        this.$message.success('分配方案已确认');
      },
      
      // 重新分配回调
      handleAllocationReallocated(allocationResult) {
        this.$message.success('重新分配完成');
      }
    }
  }
</script>

<style scoped>
</style> 